import { ref, onMounted, unref } from 'vue';
import { isFunction, get } from 'lodash-es';
import { startPullDownRefresh, stopPullDownRefresh, useReachBottom } from '@tarojs/taro';
function useSuLoading(option) {
  const {
    onLoad,
    params = {},
    dataPath = 'data.records',
    totalPath = 'data.total',
    pageKey = 'current',
    pageSizeKey = 'size',
    listBefore = null,
    listAfter = null
  } = option;
  const data = ref([]);
  const page = ref({
    current: 1,
    size: 20,
    total: 0
  });
  const hasMore = ref(true);
  const loading = ref(false);

  const loadMore = async () => {
    const query = {
      ...unref(params)
    };
    if (!hasMore.value) {
      loading.value = false;
      return;
    }
    if (!isFunction(onLoad)) {
      console.error('onLoad must be a function');
      return;
    }
    if (isFunction(listBefore)) {
      let result = listBefore(query);
      if (result === false) {
        return;
      }
    }
    loading.value = true;
    try {
      const { current, size } = page.value;
      const raw = await onLoad({
        [pageKey]: current,
        [pageSizeKey]: size,
        ...query
      });
      let payload = raw.data;
      let records = get(payload, dataPath) || [];
      let total = get(payload, totalPath) || [];
      if (isFunction(listAfter)) {
        records = listAfter(records);
      }
      data.value.push(...records);
      page.value.current++;
      page.value.total = total;
      if (data.value.length >= total) {
        hasMore.value = false;
      }
    } catch (error) {
      console.error('Error loading more data:', error);
    } finally {
      loading.value = false;
    }
  };
  const refresh = async () => {
    page.value.current = 1;
    page.value.total = 0;
    data.value = [];
    hasMore.value = true;
    await loadMore();
  };
  // 上拉加载
  const onPullDownRefresh = async () => {
    await refresh();
    stopPullDownRefresh();
  };
  onMounted(() => {
    loadMore();
    startPullDownRefresh(onPullDownRefresh);
    useReachBottom(loadMore);
  });

  return {
    data,
    page,
    hasMore,
    loading,
    loadMore,
    refresh
  };
}
export default useSuLoading;
